import axios from "axios";
import { useUserInfoStore } from "@/store/useUserInfoStore";
import type { DataResponse } from "@/types/commons/DataResponse";


const apiClient = axios.create({
  baseURL: (import.meta.env.VITE_APP_BASE_URL) ? import.meta.env.VITE_APP_BASE_URL : '/',
  timeout: 10000,
  withCredentials: true,
});


apiClient.interceptors.request.use(
  async (config) => {
    const userInfo = useUserInfoStore();

    const jwt = await refreshJwt();
    if (jwt && jwt != "") {
      userInfo.refreshJwt(jwt as string);
    }

    const token = userInfo.getJwt;
    if (token) {
      config.headers["token"] = userInfo.getJwt;
    } else {
      userInfo.toLoginpage();
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);


const refreshJwt = async () => {
  const userInfo = useUserInfoStore();

  const lastData = userInfo.getLastFreshTime;
  if (!(lastData instanceof Date)) {
    throw new Error("lastFreshTime 必须是一个有效的 Date 对象");
  }

  const differenceInMilliseconds = new Date().getTime() - lastData.getTime();

  const differenceInMinutes = differenceInMilliseconds / (1000 * 60);













  if (
    (differenceInMinutes >= userInfo.$state.refreshJwtTime ||
      !userInfo.getJwt) &&
    userInfo.getLongKey
  ) {

    try {

      const response = await axios
        .create({
          baseURL: (import.meta.env.VITE_APP_BASE_URL) ? import.meta.env.VITE_APP_BASE_URL : '',
          timeout: 10000,
          withCredentials: false,
        })
        .request({
          method: "post",
          url: "/api/login/rekey",
          data: { jwt: userInfo.getJwt, longKey: userInfo.getLongKey },
        });
      const cupkResponse = response.data as DataResponse;
      if (!response || !response.data) {
        throw new Error("Invalid response from server");
      }
      if (cupkResponse.code === 1) {
        return cupkResponse.data;
      } else {
        throw new Error(cupkResponse.msg);
      }
    } catch (error) {

      throw error;
    }
  } else {
    return null;
  }
};


apiClient.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (error.response && error.response.status === 401) {

      const userInfo = useUserInfoStore();
      userInfo.toLoginpage();
      return Promise.reject(new Error("请登录系统!"));
    }
    return Promise.reject(error);
  }
);

export default apiClient;
